<template>
  <basic-modal
    v-bind="$attrs"
    show-confirm
    :confirm-loading="confirmLoading"
    @confirm="handleConfirm"
  >
    <n-form ref="formRef" :model="roleForm">
      <n-form-item label="角色名称" path="roleName">
        <n-input
          placeholder="请输入角色名称"
          v-model:value="roleForm.roleName"
        />
      </n-form-item>
      <n-form-item label="角色编码" path="roleCode">
        <n-input
          placeholder="请输入角色编码"
          v-model:value="roleForm.roleCode"
          :disabled="actionType === ActionTypeEnum.EDIT"
        />
      </n-form-item>
      <n-form-item label="描述" path="description">
        <n-input
          placeholder="请输入角色描述"
          v-model:value="roleForm.description"
          type="textarea"
        />
      </n-form-item>
      <n-form-item label="授权">
        <n-tree
          v-model:checked-keys="roleForm.permissionIds"
          default-expand-all
          ref="permissionTree"
          show-line
          style="width: 100%"
          block-line
          :data="permissionsTree"
          expand-on-click
          checkable
        />
      </n-form-item>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { useAttrs, watch, ref, reactive } from "vue";
import { get, isEmpty } from "lodash-es";
import {
  getAllClientPermissionsList,
  addRole,
  editRole,
  getPermissionsByRoleId,
} from "@/api/role/role.api";
import type { TreeInst, TreeOption } from "naive-ui";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { PermissionVO } from "@/types/model/role/vos/role.vo";
import { IRoleForm, IRoleModalProps } from "./props";

const $emits = defineEmits(["success"]);

const props = withDefaults(defineProps<IRoleModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const $attrs = useAttrs();
watch(
  () => $attrs.show,
  (newVal) => {
    if (newVal) {
      handlGetPermissions();
    }
  }
);

watch(
  () => props.roleDetail,
  (newVal) => {
    if (!isEmpty(newVal)) {
      handleReoslveRoleDetail(newVal);
    } else {
      refresh();
    }
  }
);

const roleForm = reactive<IRoleForm>({
  roleId: "",
  roleName: "",
  roleCode: "",
  description: "",
  permissionIds: [],
  lastPermissionIds: [],
});

const checkedKeys = ref<string[]>([]);
const roleDetailPermissions = ref<any[]>([]);
const confirmLoading = ref<boolean>(false);
const permissionTree = ref<TreeInst>();
const permissionsList = ref<PermissionVO[]>([] as PermissionVO[]);
const permissionsTree = ref<TreeOption[]>([] as TreeOption[]);

const buildTree = (
  menuItems: PermissionVO[],
  parentId: string = ""
): TreeOption[] => {
  const tree: TreeOption[] = [];

  menuItems
    .filter((item) => item.parentId === parentId)
    .forEach((item) => {
      const treeNode: TreeOption = {
        key: item.id,
        label: item.name,
        // isLeaf: item.leaf, // 设置是否为叶子节点
        children: buildTree(menuItems, item.id), // 递归生成子节点
      };

      // 如果没有子节点，则删除 children 属性
      if (!treeNode.children || treeNode.children.length === 0) {
        delete treeNode.children;
      }

      tree.push(treeNode);
    });

  return tree;
};

const handleReoslveRoleDetail = async (roleDetail: any) => {
  roleForm.roleId = get(roleDetail, "id");
  roleForm.roleName = get(roleDetail, "roleName");
  roleForm.roleCode = get(roleDetail, "roleCode");
  roleForm.description = get(roleDetail, "description");
  roleForm.lastPermissionIds = [];
  roleForm.permissionIds = [];

  if (roleForm.roleId) {
    const res = await getPermissionsByRoleId(roleForm.roleId);
    console.log(res);
    const _permissionsList = get(res, "result") || [];
    const _permissionIds = _permissionsList.map((item: any) => item.id);
    roleDetailPermissions.value = _permissionsList;
    roleForm.lastPermissionIds = _permissionIds;
    roleForm.permissionIds = _permissionIds;
    checkedKeys.value = _permissionIds;
  }
};

const handlGetPermissions = async () => {
  const result = await getAllClientPermissionsList();
  const _permissionsList = get(result, "result") || [];
  permissionsList.value = _permissionsList;
  permissionsTree.value = buildTree(_permissionsList);
};

const handleAddRole = async () => {
  confirmLoading.value = true;
  try {
    await addRole(roleForm);
    $emits("success");
  } finally {
    confirmLoading.value = false;
  }
};

const handleEditRole = async () => {
  confirmLoading.value = true;
  try {
    await editRole(roleForm);
    $emits("success");
  } finally {
    confirmLoading.value = false;
  }
};

const handleConfirm = () => {
  if (permissionTree.value) {
    const checkedData = permissionTree.value.getCheckedData();

    if (!isEmpty(checkedData)) {
      roleForm.permissionIds = (get(checkedData, "keys") || []) as string[];
    }

    if (ActionTypeEnum.ADD === props.actionType) {
      handleAddRole();
    } else if (ActionTypeEnum.EDIT === props.actionType) {
      handleEditRole();
    }
  }
};

const refresh = () => {
  roleForm.roleId = "";
  roleForm.roleName = "";
  roleForm.roleCode = "";
  roleForm.description = "";
  roleForm.lastPermissionIds = [];
  roleForm.permissionIds = [];
  checkedKeys.value = [];
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
